<?php

namespace app\common\model;
use think\Model;

class ReplyArticleModel extends BaseReplyModel
{
    protected $table="zbc_reply_article";

    private $mediaImage_key="image";

    private $mediaImage_field="mediaImage";


    public function getArticles($page=1,$size=10,$field=null)
    {
        return $this->getReplys($page,$size,['created'=>'desc'],$field);
    }

    public function getReplys($page=1,$size=10,$order=null,$field=null,$type="article")
    {
        $query=self::alias("reply")
            ->leftJoin("zbc_reply_asset asset","reply.imageAssetId = asset.id")
            ->where("reply.type",$type)
            ->where("reply.parent",null)
            ->field("reply.*,asset.path");

        $count=$query->count();    

        $query=self::table($query->buildSql())
            ->field($field)
            ->alias("reply")
            ->order($order)
            ->limit(($page-1)*$size,$size)
            ->buildSql();
        
        $query=self::table($query)->alias("reply");
        return ["data"=>$query->select(),"count"=>$count];
    }

    public function getArticleWithImage($id){
        // $query=self::alias("reply")
        // ->leftJoin("zbc_reply_asset asset","reply.imageAssetId = asset.id")
        // ->where("reply.id",$id)
        // ->where("reply.type","article")
        // ->where("reply.parent",null)
        // ->field("reply.*,asset.path");

        $result=$this->with(["articles","articles.assets"])
        ->where("parent",null)
        ->find($id);
        
        return $result;
    }

    /**
     * 创建消息回复内容
     *
     * @param [type] $param
     * @return void
     */
    public function addArticles($param)
    {
        $db=$this->db(false);
        $db->startTrans();
        $id=null;
        $media_id=null;
        $isUpdate=true;

        try
        {
            foreach($param as &$article){
                $this->handleArticle($article);
            }

            $media_id=$this->upArticles($param);

            if(!$media_id) return null;
            
            $this->updateUrl($media_id,$param);
            
            $primary=$param[0];
            
            if(!array_key_exists("id",$primary)){
                $isUpdate=false;
            }

            unset($param[0]);

            $id=$this->addOrUpdate($primary);

            if($id){
                $this->addSubArticles($param);
            }
            $db->commit();
        }
        catch(\Exception $ex)
        {
            $db->rollback();
            $id=null;
            //如果新增加不成功，删除图文
            if($media_id && !$isUpdate){
                $this->getMedia()->delMaterial($media_id);
            }
        }
        
        return $id;
    }

    public function deleteArticles($param){
        $db=$this->db(false);
        $db->startTrans();
        try{
            $news=self::where("id","in",$param)->column("newsId");
            $delete=$this->where("id","in",$param)->whereOr("parent","in",$param)->delete();
            if($delete){
                foreach(array_filter($news) as $id){
                    $this->getMedia()->delMaterial($id);
                }
            }
            $db->commit();
            return true;
        }catch(\Exception $ex){
            $db->rollback();
        }

        return null;
    }

    public function findReplyArticle($id){
        $articles=$this->where("id",$id)->find();
        if(is_null($articles)) return null;

        $items=["item"=>[
            "Title"=>$articles->title,
            "Description"=>$articles->digest,
            "PicUrl"=>$articles->coverUrl,
            "Url"=>$articles->url,
        ]];
        return $items;
    }



    private function handleArticle(&$article){
        $isUpdate=true;
            
        if(!array_key_exists("id",$article)){
            $isUpdate=false;
        }

        if($isUpdate && empty($article["id"]))
        {
            unset($article["id"]);
            $isUpdate=false;
        }
        $article["type"]="article";

        $this->handleMedia($article);
    }
    /**
     * 处理回复消息 中的 上传文件
     *
     * @param [type] $param
     * @return void
     */
    private function handleMedia(&$param)
    {
        $fileName="";
        $type="";
        $typeId="";

        if(array_key_exists($this->mediaImage_key,$param))
        {
            $fileName=$param[$this->mediaImage_key];
        }

        $typeId=$this->mediaImage_field;

        if(array_key_exists($this->mediaImage_key,$param)){
            unset($param[$this->mediaImage_key]);
        }

        
        //有文件但是没有 ID 的情况 被 认为 是新的文件 需要传到微信上去
        if(!empty($fileName) && empty($param[$typeId]))
        {
            $file=$_SERVER["DOCUMENT_ROOT"] .$fileName;
            if(file_exists($file)){
                $upImage=$this->getMedia()->addMaterial($file);
                $param[$typeId]=$upImage["media_id"];
            }
        }
    }

    private function upArticles(&$param){
        $articles=[];
        $index=0;
        $newsId=array_key_exists("id",$param[0])?$param[0]["newsId"]:null;
        foreach($param as $article){
            $useUrl=array_key_exists("useUrl",$article) && $article["useUrl"];

            $reutrlUrl="";
            if($useUrl && array_key_exists("returnUrl",$article)){
                $reutrlUrl=$article["returnUrl"];
            }

            $articles[$index]=[
                "title"=>$article["title"],
                "thumb_media_id"=>$article[$this->mediaImage_field],
                "author"=>$article["author"],
                "show_cover_pic"=>"1",
                "content"=>$article["content"],
                "content_source_url"=>$reutrlUrl,
                "need_open_comment"=>"1",
                "only_fans_can_comment"=>"0",
            ];
            
            if($newsId){
                $this->getMedia()->updateNews($newsId,$index,$articles[$index]);
            }
            $index++;
        }

        if(!$newsId){
            $result=$this->getMedia()->addNews(["articles"=>$articles]);
            if($result && array_key_exists("media_id",$result)) {
                $newsId=$param[0]["newsId"]=$result["media_id"];
            }
        }

        return $newsId;
    }

    private function updateUrl($media_id,&$param){
        $result = $this->getMaterial($media_id);
        if(array_key_exists("news_item",$result)){
            $news=$result["news_item"];
            $index=0;
            foreach($param as &$article){
                // if(array_key_exists("useUrl",$article) && !$article["useUrl"]){
                //     $article["url"]=$news["url"];
                // }
                if(array_key_exists("url",$news[$index])){
                    $article["url"]=$news[$index]["url"];
                }
                $article["coverUrl"]=$news[$index]["thumb_url"];
                $index++;
            }
        }
    }

    /**
     * 添加文章列表
     *
     * @param [type] $param
     * @return void
     */
    private function addSubArticles($param)
    {
        $result=$this->articles()->saveAll($param);
        return $result;
    }

    private function addOrUpdate($param)
    {
        $isUpdate=true;
        if(!array_key_exists("id",$param)){
            $isUpdate=false;
        }

        $result=$this->isUpdate($isUpdate)->save($param);
        $result=$this->id;
        return $result;
    }

    /**
     * 关联表
     *
     * @return void
     */
    public function articles(){
        return $this->hasMany("ReplyArticleModel","parent","id");
    }

    public function articlesWithImage(){
        return $this->with(["articles","articles.assets"]);
    }

    public function assets(){
        return $this->belongsTo("ReplyAssetModel","imageAssetId","id");
    }
}